import cv2 as cv
import time
import threading


class Record:
	__writer = cv.VideoWriter()
	__frame = None
	__key = ''
	__status = False
	__video_name = ""
	cnt = 0

	def __init__(self, number):
		self.cnt = number
		print("Constructed")

	def __del__(self):
		print("Destructed")

	def Read(self, read_frame):
		self.__frame = read_frame

	def Run(self):
		if self.__writer.isOpened() and self.cnt != 0:
			if self.__status:
				self.__writer.write(self.__frame)
				self.cnt -= 1
				if self.cnt % 100 == 0:
					print(self.cnt)
			else:
				print(self.__status)

	def Write(self):
		self.__video_name = "./" + time.strftime("%H%M%S", time.localtime()) + ".avi"
		cv.imwrite(self.__video_name, self.__frame)

	def Open(self):
		if self.__status and not self.__writer.isOpened():
			self.__video_name = "./" + time.strftime("%H%M%S", time.localtime()) + ".avi"
			self.__writer.open(self.__video_name, cv.VideoWriter_fourcc(*"XVID"), 30, (640, 480))

	def Change(self, k):
		self.__key = k
		if k == 'r' or k == 'R':
			self.__status = not self.__status
			print("Status : ", self.__status)

	def Close(self):
		self.__writer.release()


def RecordVideo(number=1500):
	"""
	在无GTK时录制视频用
	:param number: 录制帧数
	:return: None
	"""
	cap = cv.VideoCapture(0)
	cap.set(cv.CAP_PROP_FRAME_WIDTH, 640)
	cap.set(cv.CAP_PROP_FRAME_HEIGHT, 480)
	cap.set(cv.CAP_PROP_FPS, 60)

	print("Cap inited")

	fps = cap.get(cv.CAP_PROP_FPS)
	# code = cv.VideoWriter_fourcc(*decode_fourcc(cap.get(cv.CAP_PROP_FOURCC)))
	size = (int(cap.get(cv.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv.CAP_PROP_FRAME_HEIGHT)))

	recorder = Record(number)
	choice = input("Now to record? (Y/N) ")
	if choice == 'Y' or choice == 'y':
		recorder.Change('r')
		recorder.Open()
		key = 'f'
		while cap.isOpened():
			ret, frame = cap.read()
			# key = input("Type in : ")

			if key == ord('s') or key == ord('S'):
				name = "./" + time.strftime("%H%M%", time.localtime()) + ".jpg"
				cv.imwrite(name, frame)

			if key == 'q':
				recorder.__del__()
				break
			# if key == ord('r') or key == ord('R') or key == 'r' or key == 'R':
			# 	key = 0
			# 	recorder.Open()

			recorder.Read(frame)
			recorder.Run()
			if recorder.cnt == 0:
				recorder.__del__()
				break
		# cv.waitKey()
		cap.release()


def RecordCut(name, pic_path):
	"""
    裁剪视频作为数据集
    :param name: 视频文件（带路径）名称
    :param pic_path: 生成的图片路径
    :return: None
    """
	video = cv.VideoCapture(name)
	counts = video.get(cv.CAP_PROP_FRAME_COUNT)
	print("This video has {} frames".format(counts))
	divisor = int(input("Type in the num you DECIDE the video"))
	for i in range(int(counts)):
		_, frame = video.read()
		if i % divisor == 0:
			cv.imwrite(pic_path + str(i // divisor) + '.jpg', frame)


# Instruction
print("输入帧数，30FPS好像")
print("输入 Y 开始录像")
#num = int(input("type in the number of frames : "))
#RecordVideo(num)

RecordCut(r".\resources\151603.avi", 'resources/')

'''

class ThisThread(threading.Thread):
	def __init__(self, name):
		threading.Thread.__init__(self)
		self.name = name

	def run(self):
		print("开启线程： " + self.name)
		# 获取锁，用于线程同步
		threadLock.acquire()
		print_time(self.name, 3)
		test()
		# 释放锁，开启下一个线程   
		threadLock.release()


def print_time(name, delay):
	time.sleep(delay)
	print("%s: %s" % (name, time.ctime(time.time())))

threadLock = threading.Lock()
threads = []

# 创建新线程
thread1 = ThisThread("Thread-1")
thread2 = ThisThread("Thread-2")

# 开启新线程
thread1.start()
thread2.start()

# 添加线程到线程列表
threads.append(thread1)
threads.append(thread2)

# 等待所有线程完成
for t in threads:
	t.join()
print("退出主线程")
# test()
'''
